<template>
    <div class="laneway-container">
        <!-- 页面标题和操作栏 -->
        <el-card class="header-card" shadow="hover">
            <div class="header-content">
                <div class="header-left">
                    <el-icon class="header-icon" :size="24">
                        <Grid />
                    </el-icon>
                    <span class="page-title">巷道管理</span>
                </div>
                <div class="header-right">
                    <el-input v-model="searchText" placeholder="搜索巷道..." :prefix-icon="Search" size="default" clearable
                        style="width: 250px; margin-right: 12px;" />
                    <el-button type="primary" :icon="Plus" @click="handleAdd">新建巷道</el-button>
                    <el-button :icon="Refresh" @click="getLanewayList">刷新</el-button>
                </div>
            </div>
        </el-card>

        <!-- 巷道列表 -->
        <el-card class="table-card" shadow="hover">
            <el-table v-loading="loading" :data="filteredTableData" style="width: 100%" stripe
                :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="lanewaycode" label="巷道编码" width="150" />
                <el-table-column prop="lanewayname" label="巷道名称" width="200" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div class="laneway-name">
                            <el-icon color="#409eff">
                                <Grid />
                            </el-icon>
                            <span style="margin-left: 8px;">{{ row.lanewayname }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="warehouseid" label="仓库ID" width="100" align="center" />
                <el-table-column prop="lanewaystate" label="巷道状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.lanewaystate)">{{ getStatusText(row.lanewaystate)
                            }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="length" label="长度" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row.length }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="width" label="宽度" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row.width }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="height" label="高度" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row.height }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="maxLocationCount" label="最大货位数" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag type="warning">{{ row.maxLocationCount }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="lanewayType" label="巷道类型" width="120" show-overflow-tooltip />
                <el-table-column prop="managerId" label="管理员ID" width="100" align="center" />
                <el-table-column prop="managerName" label="管理员" width="120" />
                <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" width="180" align="center">
                    <template #default="{ row }">
                        <el-button link type="primary" size="small" :icon="View" @click="handleView(row)">
                            查看
                        </el-button>
                        <el-button link type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button link type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :close-on-click-modal="false" draggable>
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="巷道编码" prop="lanewaycode">
                            <el-input v-model="formData.lanewaycode" placeholder="请输入巷道编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="巷道名称" prop="lanewayname">
                            <el-input v-model="formData.lanewayname" placeholder="请输入巷道名称" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="仓库ID" prop="warehouseid">
                            <el-input-number v-model="formData.warehouseid" :min="0" placeholder="请输入仓库ID"
                                style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="巷道状态" prop="lanewaystate">
                            <el-select v-model="formData.lanewaystate" placeholder="请选择状态" style="width: 100%;">
                                <el-option label="正常" :value="1" />
                                <el-option label="维护中" :value="2" />
                                <el-option label="停用" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="长度" prop="length">
                            <el-input-number v-model="formData.length" :min="0" placeholder="长度" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="宽度" prop="width">
                            <el-input-number v-model="formData.width" :min="0" placeholder="宽度" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="高度" prop="height">
                            <el-input-number v-model="formData.height" :min="0" placeholder="高度" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="最大货位数" prop="maxLocationCount">
                            <el-input-number v-model="formData.maxLocationCount" :min="0" placeholder="最大货位数"
                                style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="巷道类型" prop="lanewayType">
                            <el-input v-model="formData.lanewayType" placeholder="请输入巷道类型" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="管理员ID" prop="managerId">
                            <el-input-number v-model="formData.managerId" :min="0" placeholder="管理员ID"
                                style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="管理员名称" prop="managerName">
                            <el-input v-model="formData.managerName" placeholder="请输入管理员名称" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sortOrder">
                            <el-input-number v-model="formData.sortOrder" :min="0" placeholder="排序"
                                style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="巷道详细信息" width="800px" :close-on-click-modal="false" draggable>
            <div v-if="currentDetail" class="detail-container">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="巷道编码" label-class-name="detail-label">
                        <el-tag type="info">{{ currentDetail.lanewaycode }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="巷道名称" label-class-name="detail-label">
                        <div class="detail-title">
                            <el-icon color="#409eff">
                                <Grid />
                            </el-icon>
                            <span>{{ currentDetail.lanewayname }}</span>
                        </div>
                    </el-descriptions-item>

                    <el-descriptions-item label="仓库ID" label-class-name="detail-label">
                        {{ currentDetail.warehouseid }}
                    </el-descriptions-item>
                    <el-descriptions-item label="巷道状态" label-class-name="detail-label">
                        <el-tag :type="getStatusTagType(currentDetail.lanewaystate)">
                            {{ getStatusText(currentDetail.lanewaystate) }}
                        </el-tag>
                    </el-descriptions-item>

                    <el-descriptions-item label="长度" label-class-name="detail-label">
                        <el-tag type="info">{{ currentDetail.length }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="宽度" label-class-name="detail-label">
                        <el-tag type="info">{{ currentDetail.width }}</el-tag>
                    </el-descriptions-item>

                    <el-descriptions-item label="高度" label-class-name="detail-label">
                        <el-tag type="info">{{ currentDetail.height }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="最大货位数" label-class-name="detail-label">
                        <el-tag type="warning">{{ currentDetail.maxLocationCount }}</el-tag>
                    </el-descriptions-item>

                    <el-descriptions-item label="巷道类型" label-class-name="detail-label">
                        {{ currentDetail.lanewayType || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="排序" label-class-name="detail-label">
                        {{ currentDetail.sortOrder }}
                    </el-descriptions-item>

                    <el-descriptions-item label="管理员ID" label-class-name="detail-label">
                        {{ currentDetail.managerId || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="管理员名称" label-class-name="detail-label">
                        <el-tag v-if="currentDetail.managerName" type="success">{{ currentDetail.managerName }}</el-tag>
                        <span v-else>-</span>
                    </el-descriptions-item>

                    <el-descriptions-item label="备注" label-class-name="detail-label" :span="2">
                        {{ currentDetail.remark || '-' }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                    <el-button type="primary" @click="handleEdit(currentDetail)">编辑</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Grid, Search, Plus, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'
import myaxios from '@/Http/http'

const tableData = ref([])
const loading = ref(false)
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const dialogVisible = ref(false)
const dialogTitle = ref('新建巷道')
const formRef = ref(null)
const submitLoading = ref(false)
const isEdit = ref(false)

const detailDialogVisible = ref(false)
const currentDetail = ref(null)

const formData = ref({
    lanewaycode: '',
    lanewayname: '',
    warehouseid: 0,
    lanewaystate: 1,
    length: 0,
    width: 0,
    height: 0,
    maxLocationCount: 0,
    lanewayType: '',
    managerId: 0,
    managerName: '',
    sortOrder: 0,
    remark: ''
})

const formRules = {
    lanewaycode: [
        { required: true, message: '请输入巷道编码', trigger: 'blur' }
    ],
    lanewayname: [
        { required: true, message: '请输入巷道名称', trigger: 'blur' }
    ],
    warehouseid: [
        { required: true, message: '请输入仓库ID', trigger: 'blur' }
    ],
    lanewaystate: [
        { required: true, message: '请选择巷道状态', trigger: 'change' }
    ]
}

const filteredTableData = computed(() => {
    if (!searchText.value) return tableData.value
    return tableData.value.filter(item =>
        item.lanewayname?.toLowerCase().includes(searchText.value.toLowerCase()) ||
        item.lanewaycode?.toLowerCase().includes(searchText.value.toLowerCase()) ||
        item.lanewayType?.toLowerCase().includes(searchText.value.toLowerCase())
    )
})

const getLanewayList = async () => {
    loading.value = true
    try {
        const res = await myaxios.get('api/Laneway/GetLanewayList')
        console.log('巷道列表:', res)
        if (res.data.code === 200) {
            tableData.value = res.data.listResult || []
            total.value = tableData.value.length
            ElMessage.success('数据加载成功')
        } else {
            ElMessage.error(res.data.message || '获取数据失败')
        }
    } catch (error) {
        console.error('获取巷道列表失败:', error)
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

const handleAdd = () => {
    isEdit.value = false
    dialogTitle.value = '新建巷道'
    formData.value = {
        lanewaycode: '',
        lanewayname: '',
        warehouseid: 0,
        lanewaystate: 1,
        length: 0,
        width: 0,
        height: 0,
        maxLocationCount: 0,
        lanewayType: '',
        managerId: 0,
        managerName: '',
        sortOrder: 0,
        remark: ''
    }
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑巷道'
    formData.value = { ...row }
    dialogVisible.value = true
    detailDialogVisible.value = false
}

const handleView = (row) => {
    currentDetail.value = row
    detailDialogVisible.value = true
}

const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除巷道 "${row.lanewayname}" 吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            const res = await myaxios.delete(`api/Laneway/DeleteLaneway?id=${row.id}`)
            if (res.data.code === 200) {
                ElMessage.success('删除成功')
                getLanewayList()
            } else {
                ElMessage.error(res.data.message || '删除失败')
            }
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                let res
                if (isEdit.value) {
                    res = await myaxios.put('api/Laneway/UpdateLaneway', formData.value)
                } else {
                    res = await myaxios.post('api/Laneway/CreateLaneway', formData.value)
                }

                if (res.data.code === 200) {
                    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
                    dialogVisible.value = false
                    getLanewayList()
                } else {
                    ElMessage.error(res.data.message || '操作失败')
                }
            } catch (error) {
                console.error('提交失败:', error)
                ElMessage.error('操作失败')
            } finally {
                submitLoading.value = false
            }
        }
    })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

const getStatusText = (status) => {
    const statusMap = {
        0: '停用',
        1: '正常',
        2: '维护中'
    }
    return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
    const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
    }
    return typeMap[status] || 'info'
}

onMounted(() => {
    getLanewayList()
})
</script>

<style scoped>
.laneway-container {
    padding: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
}

.header-card {
    margin-bottom: 24px;
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.header-icon {
    color: #409eff;
}

.page-title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
}

.header-right {
    display: flex;
    align-items: center;
}

.table-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.laneway-name {
    display: flex;
    align-items: center;
    font-weight: 500;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.detail-container {
    padding: 10px 0;
}

:deep(.detail-label) {
    font-weight: 600;
    background-color: #f5f7fa;
}

.detail-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    margin: 0;
}

:deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 20px;
}

:deep(.el-dialog__headerbtn .el-dialog__close:hover) {
    color: #f0f0f0;
}

:deep(.el-table) {
    font-size: 14px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table tbody tr:hover) {
    background-color: #f5f7fa;
}

:deep(.el-button) {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.3s ease;
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
}

:deep(.el-button--primary:hover) {
    background: linear-gradient(135deg, #5568d3 0%, #6a3f8f 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

@media (max-width: 768px) {
    .laneway-container {
        padding: 16px;
    }

    .header-content {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
    }

    .header-right {
        width: 100%;
        flex-wrap: wrap;
        gap: 8px;
    }
}
</style>
